package ext.acae2.baseline.autonumber;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wt.inf.container.WTContainerRef;
import wt.log4j.LogR;
import wt.rule.ruleResource;
import wt.rule.algorithm.InvalidAlgorithmArgumentException;
import wt.rule.algorithm.RuleAlgorithm;
import wt.util.WTException;
import wt.util.WTMessage;
import ext.acae2.baseline.helper.BaselineHelper;

/**
 * @desription baseline number auto generator
 * @author cnie
 * @date 2013-3-1 下午11:09:36
 */
public class ConfigBaselineNumberGenerator implements RuleAlgorithm{
	
	
	private static final Logger LOGGER = LogR.getLogger(ConfigBaselineNumberGenerator.class
			.getName());
	private static final String RULE_RESOURCE = ruleResource.class.getName();
	
	static String FIRST_NUMBER = "001";

	/* (non-Javadoc)
	 * @see wt.rule.algorithm.RuleAlgorithm#calculate(java.lang.Object[], wt.inf.container.WTContainerRef)
	 */
	@Override
	public Object calculate(Object[] params, WTContainerRef containerRef)
			throws WTException {
		StringBuffer result=new StringBuffer();		
		for (int i = 0; i < params.length; i++) {
			if (params[i] == null) {
				String nullValue = WTMessage.getLocalizedMessage(RULE_RESOURCE,
						ruleResource.NULL_ARG);
				throw new InvalidAlgorithmArgumentException(RULE_RESOURCE,
						nullValue, new Object[] { Integer.valueOf(i) });
			}
		}
		
		String baselineLikeNum = (String) params[0];
		
		LOGGER.debug("=========baselineLikeNum===========>" + baselineLikeNum);
		
		String maxBaseLineNumber = BaselineHelper.searchBaselineLikeNumber(baselineLikeNum);
		
		LOGGER.debug("=========maxBaseLineNumber===========>" + maxBaseLineNumber);
		
		int numLength = Integer.parseInt((String) params[1]);
		
		if(StringUtils.isBlank(maxBaseLineNumber)){
			result.append(baselineLikeNum+FIRST_NUMBER);
		}else{
			result.append(baselineLikeNum);
			StringBuffer liushuiSb=new StringBuffer();
			String temp = maxBaseLineNumber.substring(maxBaseLineNumber.length()-numLength);
			int lastNum = Integer.parseInt(temp)+1;
			for(int i=0;i<numLength;i++){
				liushuiSb.append((String)params[2]);
			}
			liushuiSb.append(lastNum);
			String liushuiStr = liushuiSb.toString().substring(liushuiSb.toString().length()-numLength);
			result.append(liushuiStr);
		}
		return result;
	}

}
